package com.wbao.dianniu.tabstrip.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.KnowListAdapter;
import com.wbao.dianniu.data.KnowledgeData;
import com.wbao.dianniu.fragment.LazyLoadBaseFragment;
import com.wbao.dianniu.listener.IHeadImageListener;
import com.wbao.dianniu.listener.IKnowledgeListListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.KnowListManager;
import com.wbao.dianniu.update.HeadImageManger;
import com.wbao.dianniu.update.KnowledgeHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;

import java.util.List;

/**
 * Created by yejianjun on 2018/5/16.
 */

public class KnowFragment extends LazyLoadBaseFragment implements IKnowledgeListListener, KnowledgeHelper.IKnowledgeChangedListener, IHeadImageListener {
    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private PullToRefreshListView pullListView;
    private ListView listView;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private KnowListManager manager;
    private KnowListAdapter adapter;
    private final int TYPE = 1;
    //是否是下拉刷新
    private boolean isPullDown = true;
    private HeadImageManger headImageManger;


    public static KnowFragment instance() {
        KnowFragment view = new KnowFragment();
        return view;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDatamManager();
    }

    /*@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_fist_pager_knowledge, null);
        init(view);
        initWattingView(view);
        requestData(currentPage);
        return view;
    }*/

    private void initDatamManager() {
        manager = new KnowListManager(getContext());
        manager.addKnowledgeListListener(this);
        adapter = new KnowListAdapter(getContext(), 1);
        KnowledgeHelper.getInstance().addListener(this);
        headImageManger = HeadImageManger.getInstance();
        headImageManger.addListener(this);
    }


    private void initWattingView(View view) {
        waittingLayout = (LinearLayout) view.findViewById(R.id.waitting_layout);
        waittingProBar = (ProgressBar) view.findViewById(R.id.waitting_progress);
        waittingTV = (TextView) view.findViewById(R.id.waitting_text_desc);
    }

    private void init(View view) {
        pullListView = (PullToRefreshListView) view.findViewById(R.id.know_fragment_listview);
        pullListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullListView.setOnRefreshListener(onRefreshListener);
        listView = pullListView.getRefreshableView();
        registerForContextMenu(listView);

//        adapter.addData(new ArrayList<KnowledgeData>());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(itemClickListener);
    }

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            KnowledgeData data = (KnowledgeData) adapter.getItem(position - 1);
            ActivityUtils.intoKnowDetailActivity(getContext(), 0, data);
        }
    };


    PullToRefreshBase.OnRefreshListener2 onRefreshListener = new PullToRefreshBase.OnRefreshListener2() {
        // 下拉Pulling Down
        @Override
        public void onPullDownToRefresh() {
            //请求最新的数据
            isPullDown = true;
            currentPage = 0;
            pullUpRequest();
        }

        @Override
        public void onPullUpToRefresh() {
            //请求下一页数据
            isPullDown = false;
            currentPage++;
            pullUpRequest();
        }
    };


    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        requestData(currentPage);
    }

    private void requestData(int page) {
        manager.knowledgeList(GlobalContext.getAccountId(), TYPE, null, page * PAGE_COUNTS, PAGE_COUNTS);
    }

    @Override
    public void onKnowledgeListFailure(int errorCode, String errorMsg) {
        waittingLayout.setVisibility(View.GONE);
        pullListView.onRefreshComplete(false, false);
        Notification.toast(getContext(), errorMsg);
    }

    @Override
    public void onKnowledgeListSuccess(List<KnowledgeData> list) {
        waittingLayout.setVisibility(View.GONE);
        pullListView.onRefreshComplete(false, true);
        if (null != list) {
            if (isPullDown) {
                adapter.cleanData();
            } else {
//                adapter.addData(list);
            }
            adapter.addData(list);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeKnowledgeListListener(this);
        }
        KnowledgeHelper.getInstance().removeListener(this);
        if (null != headImageManger)
            headImageManger.removeListener(this);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("KnowFragment"); //统计页面，"MainScreen"为页面名称，可自定义
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("KnowFragment");
    }

    @Override
    public void addOneKnowledge(KnowledgeData data) {

    }

    @Override
    public void removeOneKnowledge(int knowledgeId) {
        adapter.removeOneData(knowledgeId);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void goodNotify(int knowledgeId, int isGood, int goodCount) {
        adapter.goodChanged(knowledgeId, isGood, goodCount);
    }

    @Override
    public void replyNotify(int knowledgeId, int answerCounts) {
        adapter.replyNotify(knowledgeId, answerCounts);
    }

    @Override
    public void visitorNotify(int knowledgeId, int visitorCounts) {
        adapter.visitorNotify(knowledgeId, visitorCounts);
    }

    @Override
    public void modifyOneData(int knowledgeId, KnowledgeData data) {

    }

    @Override
    public void imageChange(String headCachePath) {

    }

    @Override
    public void dataChanged(String nickName, String headPic, String sex, String signate, String label) {
        Integer sexFlag = null;
        if (sex.equals("男")) {
            sexFlag = 1;
        } else if (sex.equals("女")) {
            sexFlag = 0;
        }
        adapter.updateHeadInfo(GlobalContext.getAccountId(), nickName, headPic, sexFlag, label);
    }

    @Override
    public void partnerNotify(int partner) {
        adapter.updatePartner(GlobalContext.getAccountId(), partner);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_fist_pager_knowledge;
    }

    @Override
    protected void initView(View view) {
        init(view);
        initWattingView(view);
//        requestData(currentPage);
    }

    @Override
    public void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        requestData(currentPage);
    }
}
